package com.aorise.controller.diagnosis;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aorise.service.diagnosis.DiagnosisReportService;
import com.aorise.utils.page.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.aorise.exception.ServiceException;
import com.aorise.model.diagnosis.*;
import com.aorise.service.diagnosis.DiagnosisPlanService;
import com.aorise.utils.ConstDefine;
import com.aorise.utils.StatusDefine;
import com.aorise.utils.StatusDefineMessage;
import com.aorise.utils.json.JsonResponseData;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author:cat
 * @Desicription: 视频质量诊断报告控制器类
 * @Date:Created in 2019-06-26
 * @Modified By:
 */
@RestController
@Api(description = "视频质量诊断报告信息接口")
public class DiagnosisReportController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DiagnosisReportService diagnosisReportService;

    /**
     * 根据筛选条件进行分页查询诊断报告信息
     * HTTP 方式：GET
     * API 路径：/api/diagnosisReport/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllDiagnosisReportListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-26
     */
    @ApiOperation(value = "根据筛选条件进行分页查询诊断报告信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询诊断报告信息,提供视频质量诊断-诊断报告-查询列表使用")
    @RequestMapping(value = "/api/diagnosisReport/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllDiagnosisReportListByPage(@ApiParam(value = "起始诊断日期", required = false) @RequestParam(value = "startExecuteTime", required = false) String startExecuteTime,
                                       @ApiParam(value = "截止诊断日期", required = false) @RequestParam(value = "endExecuteTime", required = false) String endExecuteTime,
                                       @ApiParam(value = "诊断类型：1自动巡检，2人工巡检 ", required = false) @RequestParam(value = "pType", required = false) Integer pType,
                                       @ApiParam(value = "任务名称", required = false) @RequestParam(value = "pName", required = false) String pName,
                                       @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                       @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getAllDiagnosisReportListByPage");
        logger.debug("startExecuteTime：" + startExecuteTime);
        logger.debug("endExecuteTime：" + endExecuteTime);
        logger.debug("pType：" + pType);
        logger.debug("pName：" + pName);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startExecuteTime", startExecuteTime);
            map.put("endExecuteTime", endExecuteTime);
            map.put("pType", pType);
            map.put("pName", pName);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<DiagnosisReportModel> diagnosisReportModels = diagnosisReportService.getAllDiagnosisReportListByPage(map, page);
            page.setList(diagnosisReportModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getAllDiagnosisReportListByPage...msg:Get Diagnosis Report List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getAllDiagnosisReportListByPage...msg:Get Diagnosis Report List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 根据ID查询诊断报告详情
     * HTTP 方式：GET
     * API 路径：/api/diagnosisReport/id/{id}
     * 方法名：getDiagnosisReportById
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-26
     */
    @ApiOperation(value = "根据ID查询诊断报告详情", httpMethod = "GET", response = String.class, notes = "根据ID查询诊断报告详情，提供视频质量诊断-诊断报告-查询诊断报告详情使用")
    @RequestMapping(value = "/api/diagnosisReport/id/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getDiagnosisReportById(@ApiParam(value = "ID", required = true) @PathVariable(value = "id", required = true) Integer id) {

        logger.debug("Request RESTful API:getDiagnosisReportById");
        logger.debug("id" + id);
        try {
            DiagnosisReportModel diagnosisReportModel = diagnosisReportService.getDiagnosisReportById(id);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "",diagnosisReportModel).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getDiagnosisReportById...msg:Get Diagnosis Report By Id DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getDiagnosisReportById...msg:Get Diagnosis Report By Id Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 根据筛选条件进行分页查询诊断报告明细信息
     * HTTP 方式：GET
     * API 路径：/api/diagnosisReport/getAllReportCameraListByPage/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllReportCameraListByPage
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-26
     */
    @ApiOperation(value = "根据筛选条件进行分页查询诊断报告明细信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询诊断报告明细信息,提供视频质量诊断-诊断报告-详情-查询报告明细列表使用")
    @RequestMapping(value = "/api/diagnosisReport/getAllReportCameraListByPage/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllReportCameraListByPage(@ApiParam(value = "报告ID", required = true) @RequestParam(value = "reportId", required = true) Integer reportId,
                                                  @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                                  @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {
        logger.debug("Request RESTful API:getAllReportCameraListByPage");
        logger.debug("reportId：" + reportId);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("reportId", reportId);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<ReportCameraModel> reportCameraModels = diagnosisReportService.getAllReportCameraListByPage(map, page);
            page.setList(reportCameraModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getAllReportCameraListByPage...msg:Get Report Camera List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:getAllReportCameraListByPage...msg:Get Report Camera List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 导出诊断报告信息
     * HTTP 方式：GET
     * API 路径：/api/diagnosisReport/exportDiagnosisReport
     * 方法名：exportDiagnosisReport
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-26
     */
    @ApiOperation(value = "导出诊断报告信息", httpMethod = "GET", response = String.class, notes = "导出诊断报告信息，提供视频质量诊断-诊断报告-导出诊断报告信息使用")
    @RequestMapping(value = "/api/diagnosisReport/exportDiagnosisReport", method = RequestMethod.GET)
    public String exportDiagnosisReport(@ApiParam(value = "起始诊断日期", required = false) @RequestParam(value = "startExecuteTime", required = false) String startExecuteTime,
                                        @ApiParam(value = "截止诊断日期", required = false) @RequestParam(value = "endExecuteTime", required = false) String endExecuteTime,
                                        @ApiParam(value = "诊断类型：1自动巡检，2人工巡检 ", required = false) @RequestParam(value = "pType", required = false) Integer pType,
                                        @ApiParam(value = "任务名称", required = false) @RequestParam(value = "pName", required = false) String pName,
                                        HttpServletResponse response) {
        logger.debug("Request RESTful API:exportDiagnosisReport");
        logger.debug("startExecuteTime：" + startExecuteTime);
        logger.debug("endExecuteTime：" + endExecuteTime);
        logger.debug("pType：" + pType);
        logger.debug("pName：" + pName);

        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startExecuteTime", startExecuteTime);
            map.put("endExecuteTime", endExecuteTime);
            map.put("pType", pType);
            map.put("pName", pName);
            map.put("state", ConstDefine.STATE_ABLE);

            diagnosisReportService.exportDiagnosisReport(map, response);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS,
                    "", null).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:exportDiagnosisReport...msg:Export Diagnosis Report DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:exportDiagnosisReport...msg:Export Diagnosis Report Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 导出诊断报告明细信息
     * HTTP 方式：GET
     * API 路径：/api/diagnosisReport/exportReportCamera
     * 方法名：exportReportCamera
     * 方法返回类型：String
     *
     * @Author: cat
     * @Date: 2019-06-26
     */
    @ApiOperation(value = "导出诊断报告明细信息", httpMethod = "GET", response = String.class, notes = "导出诊断报告明细信息，提供视频质量诊断-诊断报告-详情-导出诊断报告明细信息使用")
    @RequestMapping(value = "/api/diagnosisReport/exportReportCamera", method = RequestMethod.GET)
    public String exportReportCamera(@ApiParam(value = "报告ID", required = true) @RequestParam(value = "reportId", required = true) Integer reportId,
                                        HttpServletResponse response) {
        logger.debug("Request RESTful API:exportReportCamera");
        logger.debug("reportId：" + reportId);

        try {
            diagnosisReportService.exportReportCamera(reportId, response);
            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS,
                    "", null).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:exportReportCamera...msg:Export Report Camera DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:exportReportCamera...msg:Export Report Camera Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 每3分钟查询执行视频诊断队列消息
     * @Author: cat
     * @Date: 2019-06-26
     */
    @Scheduled(cron = "0 */3 * * * ?")
    private void runDiagnosis(){
        try {
            logger.info("每3分钟查询执行视频诊断队列消息开始,当前时间为: {}",new Date());
            diagnosisReportService.addDiagnosisReport();
            logger.info("每3分钟查询执行视频诊断队列消息结束,当前时间为: {}",new Date());
        } catch (DataAccessException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:runDiagnosis...msg:Run Diagnosis DataAccessException");
            logger.error("error:" + e.getMessage());
        } catch (ServiceException e) {
            logger.error(
                    "controller:DiagnosisReportController. function:runDiagnosis...msg:Run Diagnosis ServiceException");
            logger.error("error:" + e.getMessage());
        } catch (Exception e) {
            logger.error(
                    "controller:DiagnosisReportController. function:runDiagnosis... msg:Run Diagnosis Exception");
            logger.error(e.getMessage());
        }
    }

}
